<div class="bg-light lter b-b wrapper-md">
  <h1 class="m-n font-thin h3">用户管理</h1>
</div>
<style>
  .pass-box i {
    display: block;
    width: 30px;
    height: 30px;
    position: absolute;
    right: 20px;
    top: 5px;
    background-image: url("img/common/open.png");
    background-size: cover;
  }
</style>

<div class="wrapper-md"  >
  <div class="panel panel-default">
    <div ng-controller="infoEditCtrl">
      <div class="row">
        <div class="col-sm-12" >
        <form name="form-contact" ng-submit="processForm()" class="form-horizontal">
          <div class="panel-heading">
            <span class="h4">
              <button class="btn btn-default btn-sm " ng-click="goBack()"><i class="fa fa-mail-reply fa-lg"></i>&nbsp; 返回</button>
            </span>

          </div>
            <div class="panel-body">
              <div class="panel-heading">
                <span class="h4" style="color: blue;">用户信息</span>
              </div>
              <div class="form-group">
                <label class="col-sm-1 control-label">用户角色</label>
                <div class="col-sm-5">
                  <ui-select multiple ng-model="multipleDemo.selectedPeopleWithGroupBy" theme="bootstrap" ng-disabled="disabled">
                  <ui-select-match placeholder="部门">{{$item.ClassName}} &lt;{{$item.ClassRemark}}&gt;</ui-select-match>
                  <ui-select-choices  repeat="person in people | propsFilter: {ClassName: $select.search, Id: $select.search}">
                  <div ng-bind-html="person.ClassName | highlight: $select.search"></div>
                  <small>
                  编号: <span ng-bind-html="''+person.Id | highlight: $select.search"></span>
                  </small>
                  </ui-select-choices>
                  </ui-select>
                </div>
                <label class="col-sm-1 control-label">用户名称</label>
                <div class="col-sm-5">
                <input type="text" class="form-control" placeholder="用户名称" ensure-unique="UserName" name="UserName" id="UserName" ng-model="contact.UserName" required ng-blur="isUserName()">
                </div>
              </div>

          <div class="line line-dashed b-b line-lg pull-in"></div>
              <div class="form-group">
              <label class="col-sm-1 control-label">密码</label>
                <div class="col-sm-5 pass-box" id="ps">
                <input type="password" id="psinp" class="form-control" placeholder="密码" ng-model="contact.UserPassword" required ><i state="off" id="psi" onclick="qieHuan();"></i>
                </div>

                <label  class="col-sm-1 control-label">用户昵称</label>
                <div class="col-sm-5">
                <input type="text" class="form-control" placeholder="用户昵称" ng-model="contact.UserNickname">
                </div>
              </div>
          <div class="line line-dashed b-b line-lg pull-in"></div>

            <div class="form-group">
              <label class="col-sm-1 control-label">有效时间</label>
                <div class="col-sm-2">
                <input type="text"  ng-model="contact.ValidityBegin" id="validityBegin"  onFocus="WdatePicker({maxDate:'#F{$dp.$D(\'validityEnd\')||\'2020-10-01\'}',dateFmt:'yyyy-MM-dd'})"  class="form-control" required /> 
                </div>
                <div class="col-sm-2">
                <input type="text"  ng-model="contact.ValidityEnd" id="validityEnd"   onFocus="WdatePicker({minDate:'#F{$dp.$D(\'validityBegin\')}',maxDate:'2020-10-01',dateFmt:'yyyy-MM-dd'})" class="form-control" required />
                </div>
            </div>
          <div class="line line-dashed b-b line-lg pull-in"></div>



            <div class="form-group">
              <label class="col-sm-1 control-label">真实姓名</label>
              <div class="col-sm-5">
              <input type="text" class="form-control" placeholder="真实姓名" ng-model="contact.UserRealname"  >
              </div>
              <label  class="col-sm-1 control-label">等级</label>
              <div class="col-sm-5">
              <input type="Number" class="form-control" placeholder="等级" ng-model="contact.UserLevel"  >
              </div>
            </div>
          <div class="line line-dashed b-b line-lg pull-in"></div>


            <div class="form-group">
              <label class="col-sm-1 control-label">手机</label>
              <div class="col-sm-5">
                <input type="text" class="form-control" placeholder="手机" ng-model="contact.UserPhone"  >
              </div>
              <label  class="col-sm-1 control-label">邮箱</label>
              <div class="col-sm-5">
                <input type="text" class="form-control" placeholder="邮箱" ng-model="contact.UserEmail"  >
              </div>
            </div>
          <div class="line line-dashed b-b line-lg pull-in"></div>
            <div class="form-group">
              <label class="col-sm-1 control-label">备注</label>  
              <div class="col-sm-10">
                 <textarea class="form-control" ng-model="contact.UserRemark"  rows="6" placeholder="备注"></textarea>
              </div>
            </div>
          <div class="line line-dashed b-b line-lg pull-in"></div>
            <div class="form-group">
              <label class="col-sm-1 control-label">头像</label>  
                <div class="col-sm-5">
                <input type="text" class="form-control" placeholder="" ng-model="contact.UserSmallIcon" >
                </div>
            </div>
          <div class="line line-dashed b-b line-lg pull-in"></div>
        </div>


  <!--隐藏字段-->
<input type="hidden"  ng-model="contact.Id"  >
<input type="hidden"  ng-model="contact.UserUuid"  >
<input type="hidden"  ng-model="contact.AccessToken"  >
<input type="hidden"  ng-model="contact.UserInterest"  >
<input type="hidden"  ng-model="contact.UserRecentBrowse"  >
<input type="hidden"  ng-model="contact.UserLoginCount"  >
<input type="hidden"  ng-model="contact.AutoAudit"  >
<input type="hidden"  ng-model="contact.UserIsDiaplay"  >
<input type="hidden"  ng-model="contact.UserDisplayOrder"  >
<input type="hidden"  ng-model="contact.AccountId"  >
<input type="hidden"  ng-model="contact.AdderId"  >
<input type="hidden"  ng-model="contact.AdderName"  >
<input type="hidden"  ng-model="contact.AddTime"  >
<input type="hidden"  ng-model="contact.LastLoginTime"  >
<input type="hidden"  ng-model="contact.LastLoginIp"  >
<input type="hidden"  ng-model="contact.UpdaterId"  >
<input type="hidden"  ng-model="contact.UpdaterName"  >
<input type="hidden"  ng-model="contact.UpdateTime"  >
<input type="hidden"  ng-model="contact.DelFlag" ng-init="contact.DelFlag='0'" >

    <!--隐藏字段-->






            <footer class="panel-footer text-right bg-light lter">
              <button type="submit" class="btn btn-success">提交</button>
            </footer>
          </div>
        </form>
      </div>
    </div>
   
</div>
</div>




</div>
<!--angularjs-->
<script type="text/javascript">
//输入密码时 的状态切换
var ele_pass_box = document.getElementById("ps");
var ele_pass = document.getElementById("psinp");
var ele_eye = document.getElementById("psi");
 
function qieHuan(){
    var state = ele_eye.getAttribute('state');
    if (state === "off") {
      ele_pass.setAttribute("type", "text");
      ele_eye.setAttribute("state", "on");
      ele_eye.style.backgroundImage = 'url("img/common/open.png")';
    }
    else {
      ele_pass.setAttribute("type", "password");
      ele_eye.setAttribute("state", "off");
      ele_eye.style.backgroundImage = 'url("img/common/close.png")';
    }
  }

  'use strict';
app.controller('infoEditCtrl', function ($scope, $state, $stateParams,$http,$window) {
  $scope.userEnable = true;


//验证用户名是否唯一
$scope.isUserName=function(){
  
  var UserName = $scope.contact.UserName;
  if(UserName != ""){
     var delUrl =   API_URL+"user_info?query=delflag:0,UserName:"+UserName;
      $.ajax({  
                  async : false, //是否异步  
                  cache : false, //是否使用缓存  
                  type : 'get', //请求方式,post  
                  dataType : "json", //数据传输格式  
                  url : delUrl, //请求链接  
                  // data: JSON.stringify(formData),
                  error : function() {  
                      console.log('亲，网络有点不给力呀！');  

                  },  
                  success : function(data) { 
                    // console.log(data[0].UserName);
                       if(data != null){
                         //required();
                         alert("此用户名义存在")
                       }
                  
                  }  
             }); 
  }
   

};



//返回按钮：开始
$scope.$window = $window;
    $scope.goBack = function() {
      $state.go('app.user.user');
    };


//返回按钮：结束


var classId = $stateParams.classId;

var infoId = $stateParams.infoId;
$scope.pwdShow=function(){
  $scope.contact.UserPassword2 = $scope.contact.UserPassword;
};

 //如果infoId不为空，查询详情：开始
  if(''!=infoId){
    var getInfoUrl = API_URL+"user_info?query=delflag:0,id:"+infoId+"&sortby=updateTime&order=desc"; 
      $http.get(getInfoUrl).success(function (response) {
       var obj = response[0];
       obj.UserLevel = Number(obj.UserLevel);

       obj.ValidityBegin = getDateTime(obj.ValidityBegin);
       obj.ValidityEnd = getDateTime(obj.ValidityEnd);
       if("0" == obj.UserEnable){
        $scope.userEnable = false;
       }
      $scope.contact = obj;
    });
  }
//如果infoId不为空，查询详情：结束

  //表单提交开始
$scope.processForm= function (){


  //1.参数处理

//发起POST请求
var postInfoUrl = API_URL+"user_info";
var formData =  $scope.contact;
  //1.参数处理
  
    formData.ValidityBegin = forDbDateTime($('#validityBegin').val());
    formData.ValidityEnd = forDbDateTime($('#validityEnd').val());
    formData.AddTime = getNowDBFormatDate();
    formData.UpdateTime = getNowDBFormatDate();
    formData.LastLoginTime=getNowDBFormatDate(); 
    formData.UserLevel=formData.UserLevel + '';
    formData.AdderId = 1;
    formData.AdderName = '1';
    formData.UpdaterId = 1;
    formData.UpdaterName = '1';
    formData.UserUuid='';
    formData.UserEnable = '1';
    if(false == $scope.userEnable){
      formData.UserEnable = '0';
    }
  var userclass = $scope.multipleDemo.selectedPeopleWithGroupBy;
    
//var originUserId = $scope.contact.UserId;
  if("undefined"!=typeof(formData.Id)){
     var userId = Number(infoId);
          $.ajax({  
                  async : false, //是否异步  
                  cache : false, //是否使用缓存  
                  type : 'put', //请求方式,post  
                  dataType : "json", //数据传输格式  
                  url : postInfoUrl+'/'+infoId, //请求链接  
                  data: JSON.stringify(formData),
                  error : function() {  
                      console.log('亲，网络有点不给力呀！');  
                  },  
                  success : function(data) {
                    //得到了 修改人的Id
                    var url =  API_URL+"r_user_2_class";
                   
                    var objs = MY_ASYNC_AJAX(url+"?query=delflag:0,UserId:"+userId);
                 
                    if(objs!=null&&objs.length>0){
                    for(var i =0; i<objs.length;i++){
                    $.ajax({  
                          async : false, //是否异步  
                          cache : false, //是否使用缓存  
                          type : 'delete', //请求方式,post  
                          url : url+'/'+objs[i].Id, //请求链接  
                          error : function() {  
                              console.log('亲，网络有点不给力呀！');  
                          },  
                          success : function(data) {
                       
                     
                          }  
                     }); 

                    }
                  }
                       var classArr =  $scope.multipleDemo.selectedPeopleWithGroupBy;
                      
                    if(''!= classArr){

                      for(var i =0;i<classArr.length;i++){
                         var pushClassUrl =  API_URL+"r_user_2_class";
                          var classFormData = {};
                             classFormData.AddTime = getNowDBFormatDate();
                             classFormData.AdderId = 1;
                             classFormData.AdderName = '1';
                             classFormData.delflag = '0';
                             classFormData.UserId = userId;
                             classFormData.ClassId = classArr[i].Id;
                               $.ajax( {  
                                async : false, //是否异步  
                                cache : false, //是否使用缓存  
                                type : 'post', //请求方式,post  
                                dataType : "json", //数据传输格式  
                                url : pushClassUrl, //请求链接  
                                data: JSON.stringify(classFormData),
                                error : function() {  
                                    console.log('亲，网络有点不给力呀！');  
                                },  
                                success : function(data) { 
                               
                                }  
                           }); 
                        
                      }
                    }
                  top.layer.msg('修改成功', {icon: 6});

                  //2.成功跳转页面
                  $state.go('app.user.user');
                  }  
              }); 


         }else{

         $.ajax( {  
                  async : false, //是否异步  
                  cache : false, //是否使用缓存  
                  type : 'post', //请求方式,post  
                  dataType : "json", //数据传输格式  
                  url : postInfoUrl, //请求链接  
                  data: JSON.stringify(formData),
                  error : function() {  
                      console.log('亲，网络有点不给力呀！');  
                  },  
                  success : function(data) { 
                    var classArr =  $scope.multipleDemo.selectedPeopleWithGroupBy;
                    if(''!= classArr){
                      for(var i =0;i<classArr.length;i++){
                        var pushClassUrl =  API_URL+"r_user_2_class";
                        var exists = MY_ASYNC_AJAX(pushClassUrl+"?query=delflag:0,UserId:"+data[0].Id+",ClassId:"+classArr[i].Id);
                        if(null==exists){
                          var classFormData = {};
                             classFormData.AddTime = getNowDBFormatDate();
                             classFormData.AdderId = 1;
                             classFormData.AdderName = '1';
                             classFormData.delflag = '0';
                             classFormData.UserId = data[0].Id;
                             classFormData.ClassId = classArr[i].Id;

                               $.ajax( {  
                                async : false, //是否异步  
                                cache : false, //是否使用缓存  
                                type : 'post', //请求方式,post  
                                dataType : "json", //数据传输格式  
                                url : pushClassUrl, //请求链接  
                                data: JSON.stringify(classFormData),
                                error : function() {  
                                    console.log('亲，网络有点不给力呀！');  
                                },  
                                success : function(data) { 
                               
                                }  
                           }); 
                        }
                      }
                    }




                    top.layer.msg('保存成功', {icon: 6});
                 //2.成功跳转页面
                 $state.go('app.user.user');
                  }  
             }); 

          }


}

 //表单提交结束

});




// this is a lazy load controller, 
// so start with "app." to register this controller

app.filter('propsFilter', function() {
    return function(items, props) {
        var out = [];

        if (angular.isArray(items)) {
          items.forEach(function(item) {
            var itemMatches = false;

            var keys = Object.keys(props);
            for (var i = 0; i < keys.length; i++) {
              var prop = keys[i];
              var text = props[prop].toLowerCase();
              if (item[prop].toString().toLowerCase().indexOf(text) !== -1) {
                itemMatches = true;
                break;
              }
            }

            if (itemMatches) {
              out.push(item);
            }
          });
        } else {
          // Let the output be the input untouched
          out = items;
        }

        return out;
    };
})



//选择类型下拉框
app.controller('SelectCtrl', function($scope, $http, $stateParams,$timeout) {



        $scope.disabled = undefined;
        $scope.searchEnabled = undefined;

        $scope.enable = function() {
        $scope.disabled = false;
        };

        $scope.disable = function() {
        $scope.disabled = true;
        };

        $scope.enableSearch = function() {
        $scope.searchEnabled = true;
        }

        $scope.disableSearch = function() {
        $scope.searchEnabled = false;
        }

        $scope.clear = function() {
        $scope.person.selected = undefined;
        $scope.address.selected = undefined;
        $scope.country.selected = undefined;
        };


        $scope.personAsync = {selected : "wladimir@email.com"};
        $scope.peopleAsync = [];


        $scope.counter = 0;
        $scope.someFunction = function (item, model){
        $scope.counter++;
        $scope.eventResult = {item: item, model: model};
        };

        $scope.removed = function (item, model) {
        $scope.lastRemoved = {
            item: item,
            model: model
        };
        };

        $scope.person = {};

        var infoUrl = API_URL+"user_class?query=delflag:0";

        var formData =  MY_ASYNC_AJAX(infoUrl);
        $scope.people = formData;
        $scope.multipleDemo = {};
        $scope.multipleDemo.colors = ['Blue','Red'];

        //已经存在的
        var infoId = $stateParams.infoId;
         $scope.multipleDemo.selectedPeopleWithGroupBy = [];

         if(''!=infoId&& undefined!=infoId){
            var classUrl = API_URL+"r_user_2_class?query=delflag:0,UserId:"+infoId;
            var classList = MY_ASYNC_AJAX(classUrl);
             console.log('获取classList：'+classList);
          if(null !=  classList){
            for(var i= 0;i<classList.length;i++){
               var infoClassUrl = API_URL+"user_class?query=delflag:0,Id:"+classList[i].ClassId;
               var infoClass = MY_ASYNC_AJAX(infoClassUrl)[0];
                  for(var j=0;j<formData.length;j++){
                  if($scope.people[j].Id == infoClass.Id){

                    $scope.multipleDemo.selectedPeopleWithGroupBy.push($scope.people[j]);
                    break;
                  }
               }
                      
            }
          }
        }else{
               var classId = $stateParams.classId;
               if(''!=classId&&undefined!=classId){
                    for(var j=0;j<formData.length;j++){
                  if($scope.people[j].Id == classId){

                    $scope.multipleDemo.selectedPeopleWithGroupBy.push($scope.people[j]);
                    break;
                  }
               }
              }
             
        }
      
});

</script>
<!--angularjs-->









